<template>
  <div class="content" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px">
      <el-button
        v-hasPermi="['config:drawing-process-create-up:upload']"
        v-if="formType.includes('update')"
        type="primary"
        :disabled="formLoading"
        @click="handleUpload"
      >
        数据导入
      </el-button>
      <el-button
        v-hasPermi="['config:drawing-process-create-up:upload']"
        v-if="formType.includes('create')"
        type="primary"
        :disabled="formLoading"
        @click="handleUploadCreate"
      >
        数据导入
      </el-button>
      <el-button
        v-hasPermi="['config:drawing-process-create-up:export']"
        type="primary"
        :disabled="formLoading"
        @click="handleExport"
      >
        数据导出
      </el-button>
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['config:drawing-process-create-up:save']"
        >保 存</el-button
      >
      <el-button @click="close">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <div class="text-16px font-700 mb-20px">基本信息</div>
      <el-form
        class="-mb-15px"
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :inline="true"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-form-item label="流程表编号" prop="templateNumber">
          <el-input
            v-model="formData.templateNumber"
            placeholder="流程表编号"
            clearable
            disabled
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input
            v-model="formData.version"
            placeholder="版本号"
            clearable
            disabled
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <el-select
            v-model="formData.productType"
            placeholder="请选择产品类型"
            clearable
            class="!w-220px"
          >
            <el-option
              v-for="(dict, index) in productTypeData"
              :key="index"
              :label="dict.productType"
              :value="dict.productType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="dictEnableStatus">
          <el-select v-model="formData.dictEnableStatus" placeholder="请选择状态">
            <el-option
              v-for="(dict, index) in getIntDictOptions('dict_enable_status')"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 基本参数 -->
      <div class="text-16px font-700 mb-20px mt-20px">基本参数</div>
      <el-table ref="multipleTableRef" v-loading="loading" :data="list" border>
        <el-table-column label="行号" align="center" type="index" width="55" />
        <el-table-column label="字段一" align="center" prop="name1">
          <template #default="scope">
            <el-input v-nextInput="'name1'" name="name1" :maxlength="6" v-model="scope.row.name1" />
          </template>
        </el-table-column>
        <el-table-column label="字段二" align="center" prop="name2">
          <template #default="scope">
            <el-input v-nextInput="'name2'" name="name2" :maxlength="6" v-model="scope.row.name2" />
          </template>
        </el-table-column>
        <el-table-column label="字段三" align="center" prop="name3">
          <template #default="scope">
            <el-input v-nextInput="'name3'" name="name3" :maxlength="6" v-model="scope.row.name3" />
          </template>
        </el-table-column>
        <el-table-column label="字段四" align="center" prop="name4">
          <template #default="scope">
            <el-input v-nextInput="'name4'" name="name4" :maxlength="6" v-model="scope.row.name4" />
          </template>
        </el-table-column>
        <el-table-column label="字段五" align="center" prop="name5">
          <template #default="scope">
            <el-input v-nextInput="'name5'" name="name5" :maxlength="6" v-model="scope.row.name5" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button link type="primary" @click="addLine">新增行</el-button>
            <el-button
              v-if="scope.$index !== 0"
              link
              type="danger"
              @click="deleteLine(scope.$index)"
              >删除行</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 校对参数 -->
      <div class="text-16px font-700 mb-20px mt-20px">校对参数</div>
      <div class="pb-20px">
        <el-table
          ref="multipleTableRef"
          v-loading="loading"
          :data="verifyParams"
          :span-method="arraySpanMethod"
          border
        >
          <el-table-column label="设备/部件名称" align="center" prop="partName" width="200">
            <template #default="scope">
              <div class="partPlus">
                <el-input
                  v-nextInput="'partName'"
                  name="partName"
                  @change="partClick(scope.row.partName)"
                  v-model="scope.row.partName"
                />
                <el-button link type="primary" @click="addSetUp"
                  ><Icon icon="ep:circle-plus" class="ml-5px"
                /></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="项目" align="center" prop="projectName" width="300">
            <template #default="scope">
              <div class="partPlus">
                <el-input
                  v-nextInput="'projectName'"
                  name="projectName"
                  v-model="scope.row.projectName"
                />
                <el-button link type="primary" @click="addProject(scope)"
                  ><Icon icon="ep:circle-plus" class="ml-5px"
                /></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="合同要求/总图尺寸" align="center" prop="requirementOrSize" />
          <el-table-column label="设计值" align="center" prop="designValue" />
          <el-table-column label="校对值" align="center" prop="verifyValue" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button
                v-if="scope.$index != findUpIndex(scope.row.name)"
                link
                type="primary"
                @click="paramsUp(scope.$index)"
                >上移</el-button
              >
              <el-button
                v-if="scope.$index != findLastData(scope.row.name)"
                link
                type="primary"
                @click="paramsDown(scope.$index)"
                >下移</el-button
              >
              <el-button link type="danger" @click="verifyDeleteLine(scope.$index, scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-scrollbar>
  </div>
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 数据导入 -->
  <CusUploadFile ref="cusUploadFile" @refresh="open" />
  <!-- 新增数据导入 -->
  <CusCreateFile ref="cusCreateFile" @refresh="readyCreateData" />
</template>
<script setup lang="ts">
import download from '@/utils/download'
import { getIntDictOptions } from '@/utils/dict'
import * as DrawingProcessTemplateApi from '@/api/config/drawingProcessTemplate'
const { query } = useRoute() // 路由的查询
import { useTagsViewStore } from '@/store/modules/tagsView'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(false) // 表单的加载
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  templateNumber: undefined,
  productType: undefined,
  dictEnableStatus: undefined,
  version: undefined
})
const formRules = reactive({
  productType: [{ required: true, message: '产品类型不能为空', trigger: 'change' }],
  dictEnableStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

// 基本参数
const list = ref([
  {
    name1: '',
    name2: '',
    name3: '',
    name4: '',
    name5: ''
  }
])
// 校对参数
const verifyParams = ref([
  {
    partName: '',
    name: '',
    projectName: '',
    requirementOrSize: '',
    designValue: '',
    verifyValue: '',
    remark: ''
  }
])

// input输入事情
const partClick = (value) => {
  let timerId
  clearTimeout(timerId)
  timerId = setTimeout(() => {
    const data = JSON.parse(JSON.stringify(verifyParams.value))
    const a = [] as any
    data.map((item) => {
      if (item.name != item.partName) {
        a.push({
          newValue: item.partName,
          oldValue: item.name
        })
      }
    })
    verifyParams.value.map((item) => {
      let index = a.findIndex((val) => val.oldValue == item.name)
      if (index != -1 && value != '') {
        item.name = a[index].newValue
      }
    })
  }, 300)
}

// 合并数据
const arraySpanMethod = ({ rowIndex, columnIndex }) => {
  switch (columnIndex) {
    case 0: // 第一列
      return mergeCol('name', rowIndex)
  }
}

/** 打开弹窗 */
const open = async () => {
  const type = query.type as any
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (query.id != 'undefined') {
    let id = query.id as any
    formLoading.value = true
    try {
      const data = await DrawingProcessTemplateApi.getDrawingProcessTemplate(id)
      formData.value.templateNumber = data.templateNumber
      formData.value.productType = data.productType
      formData.value.version = data.version
      formData.value.dictEnableStatus = data.dictEnableStatus
      list.value = data.baseParamsMaps
      // list.value.shift()
      data.verifyParams.map((item) => {
        // 将 partName 映射到 name 变量
        item.name = item.partName
        // 将 item 添加到 verifyParams 数组中
        verifyParams.value.push(item)
      })
      verifyParams.value.shift()
    } finally {
      formLoading.value = false
    }
  }
}

// 数据导入
const cusUploadFile = ref()
const handleUpload = () => {
  verifyParams.value = [
    {
      partName: '',
      name: '',
      projectName: '',
      requirementOrSize: '',
      designValue: '',
      verifyValue: '',
      remark: ''
    }
  ]
  let id = query.id
  cusUploadFile.value.open(
    '/config/drawing-process-verify-params-conf/get-import-template',
    `/config/drawing-process-verify-params-conf/import/${id}`
  )
}

// 新增数据导入
const cusCreateFile = ref()
const handleUploadCreate = () => {
  verifyParams.value = [
    {
      partName: '',
      name: '',
      projectName: '',
      requirementOrSize: '',
      designValue: '',
      verifyValue: '',
      remark: ''
    }
  ]
  cusCreateFile.value.open(
    '/config/drawing-process-verify-params-conf/get-import-template',
    '/config/drawing-process-verify-params-conf/import-template'
  )
}

// 新增数据导入回显
const readyCreateData = (data) => {
  data.map((item) => {
    item.name = item.partName
    verifyParams.value.push(item)
  })
  verifyParams.value.shift()
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const dataVal = JSON.parse(JSON.stringify(verifyParams.value))
    const a = [] as any
    dataVal.map((item) => {
      if (item.name != item.partName) {
        a.push({
          newValue: item.partName,
          oldValue: item.name
        })
      }
    })
    verifyParams.value.map((item) => {
      let index = a.findIndex((val) => val.oldValue == item.name)
      if (index != -1) {
        item.partName = a[index].oldValue
      }
    })
    verifyParams.value.forEach((item) => {
      delete (item as any).name
    })
    // const data = formData.value as unknown as DrawingProcessTemplateApi.DrawingProcessTemplateVO
    if (formType.value === 'create') {
      let data = {
        templateCode: '',
        dictEnableStatus: formData.value.dictEnableStatus,
        productType: formData.value.productType,
        baseParamsMaps: list.value,
        verifyParams: verifyParams.value
      }
      await DrawingProcessTemplateApi.createDrawingProcessTemplate(data)
      message.success(t('common.createSuccess'))
      goBack()
    } else {
      if (query.id != 'undefined') {
        let id = query.id
        let data = {
          id: id,
          version: formData.value.version,
          templateNumber: formData.value.templateNumber,
          dictEnableStatus: formData.value.dictEnableStatus,
          productType: formData.value.productType,
          baseParamsMaps: list.value,
          verifyParams: verifyParams.value
        }
        await DrawingProcessTemplateApi.updateDrawingProcessTemplate(data)
        message.success(t('common.updateSuccess'))
        goBack()
      }
    }
  } finally {
    formLoading.value = false
  }
}

/** 基本参数 */
// 新增
const addLine = () => {
  const data = {
    name1: '',
    name2: '',
    name3: '',
    name4: '',
    name5: ''
  }
  list.value.push(data)
}
// 移除行
const deleteLine = (index) => {
  list.value.splice(index, 1)
}

/** 校对参数 */
// 设置新增
const iddexAdd = ref(0)
const addSetUp = () => {
  iddexAdd.value++
  const data = {
    partName: `设备${iddexAdd.value + 1}`,
    name: `设备${iddexAdd.value + 1}`,
    projectName: '',
    requirementOrSize: '',
    designValue: '',
    verifyValue: '',
    remark: ''
  }
  verifyParams.value.push(data)
}
// 下移
const findLastData = (name: string) => {
  if (name != undefined) {
    let isLast = verifyParams.value.findLastIndex((item) => item.name === name)
    return isLast
  }
}
// 上移
const findUpIndex = (name: string) => {
  if (name != undefined) {
    let isLast = verifyParams.value.findIndex((item) => item.name === name)
    return isLast
  }
}
// 项目新增
const addProject = (res) => {
  const data = {
    partName: res.row.name,
    name: res.row.name,
    projectName: '',
    requirementOrSize: '',
    designValue: '',
    verifyValue: '',
    remark: ''
  }
  let nameIndex = verifyParams.value.findLastIndex((item) => {
    return item.partName === res.row.name
  })
  if (nameIndex !== -1) {
    verifyParams.value.splice(res.$index + 1, 0, data)
  }
}

// 上移
const paramsUp = (index) => {
  if (index > 0) {
    const temp = verifyParams.value[index]
    verifyParams.value.splice(index, 1)
    verifyParams.value.splice(index - 1, 0, temp)
  }
}

// 下移
const paramsDown = (index) => {
  if (index < verifyParams.value.length - 1) {
    const temp = verifyParams.value[index]
    verifyParams.value.splice(index, 1)
    verifyParams.value.splice(index + 1, 0, temp)
  }
}

// 校队删除
const verifyDeleteLine = async (index, id?: number) => {
  verifyParams.value.splice(index, 1)
  if (id) {
    await DrawingProcessTemplateApi.deleteDrawingProcessConf(id)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    templateNumber: undefined,
    productType: undefined,
    dictEnableStatus: undefined,
    version: undefined
  }
  formRef.value?.resetFields()
}

// 关闭
const close = () => {
  ElMessageBox.confirm('是否保存填写内容?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      submitForm()
    })
    .catch(() => {
      goBack()
    })
}

// 合并表格方法
const mergeCol = (id, rowIndex) => {
  let idName = verifyParams.value[rowIndex][id]
  if (rowIndex > 0) {
    // 非第一行
    if (verifyParams.value[rowIndex][id] !== verifyParams.value[rowIndex - 1][id]) {
      let i = rowIndex
      let num = 0
      while (i < verifyParams.value.length && verifyParams.value[i][id] === idName) {
        i++
        num++
      }
      return {
        rowspan: num,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 1
      }
    }
  } else {
    // 第一行
    let i = rowIndex
    let num = 0
    while (i < verifyParams.value.length && verifyParams.value[i][id] === idName) {
      i++
      num++
    }
    return {
      rowspan: num,
      colspan: 1
    }
  }
}

// 产品类型
const productTypeData = ref<any[]>([])
const dropDown = async () => {
  loading.value = true
  try {
    const data = await DrawingProcessTemplateApi.getDropDown()
    productTypeData.value = data
  } finally {
    loading.value = false
  }
}
/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}

// 导出数据
const downloadFun = async () => {
  const val = exportRef.value.params
  let id = query.id
  if (query.id == 'undefined') {
    return message.notifyError('模板不存在')
  }
  let params = {
    fileName: val.name,
    configDrawingProcessTemplateId: id,
    ids: ''
  }
  if (val.range === 'all') {
    params.ids = ''
  } else {
    params.ids = ''
  }
  DrawingProcessTemplateApi.exportParamsConf(params).then((res) => {
    download.excel(res, val.name)
  })
}

// 返回
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  route.push({
    path: '/config/config/cartographicManagement/drawing-process-template'
  })
}
const contentHeight = ref(0)
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 127
  await open()
  dropDown()
})
</script>
<style lang="scss" scoped>
.partPlus {
  display: flex;
  justify-content: center;
  align-items: center;
}
.content {
  padding: 10px;
  background: #fff;
}
</style>
